package com.yunbiao.ybbusstopplate.ui.activity;

import android.app.ProgressDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.UiMessageUtils;
import com.example.library_hy_advert.HYAdvert;
import com.tencent.upgrade.core.DefaultUpgradeStrategyRequestCallback;
import com.tencent.upgrade.core.UpgradeManager;
import com.yunbiao.communication.ServiceManager;
import com.yunbiao.ybbusstopplate.BuildConfig;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.BaseActivity;
import com.yunbiao.ybbusstopplate.base.Constants;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.base.alive.KeepAliveService;
import com.yunbiao.ybbusstopplate.doublescreen.SecondaryPresentation;
import com.yunbiao.ybbusstopplate.message.CoreInfoHandler;
import com.yunbiao.ybbusstopplate.play_sync.ClientSocket;
import com.yunbiao.ybbusstopplate.play_sync.ServerSocket;
import com.yunbiao.ybbusstopplate.refactoring.Config;
import com.yunbiao.ybbusstopplate.refactoring.ui.dalian.ZHIDAParser;
import com.yunbiao.ybbusstopplate.refactoring.ui.dalian.DalianHeadInfoFragment;
import com.yunbiao.ybbusstopplate.refactoring.ui.dalian.DalianNodeSiteFragment;
import com.yunbiao.ybbusstopplate.refactoring.ui.fengxian.FengxianNodeSiteFragment;
import com.yunbiao.ybbusstopplate.refactoring.ui.fengxian.FengxianHeadInformationFragment;
import com.yunbiao.ybbusstopplate.refactoring.ui.fengxian.TONGDA2020Parser;
import com.yunbiao.ybbusstopplate.refactoring.ui.spain.SpainMainFragment;
import com.yunbiao.ybbusstopplate.serialport.SerTool;
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig;
import com.yunbiao.ybbusstopplate.refactoring.ui.yibin.ZHXPortAgreement;
import com.yunbiao.ybbusstopplate.serialport.agreement.AgreementTool;
import com.yunbiao.ybbusstopplate.serialport.agreement.LSPortAgreement;
import com.yunbiao.ybbusstopplate.ui.dialog.LetterErrorDialogTool;
import com.yunbiao.ybbusstopplate.ui.fragment.ConfigFragment;
import com.yunbiao.ybbusstopplate.ui.fragment.LeshanMainFragment;
import com.yunbiao.ybbusstopplate.ui.fragment.LogFragment;
import com.yunbiao.ybbusstopplate.ui.fragment.MainFragment;
import com.yunbiao.ybbusstopplate.ui.fragment.ThreeAreaMainFragment;
import com.yunbiao.ybbusstopplate.ui.fragment.VerifyFragment;
import com.yunbiao.ybbusstopplate.refactoring.ui.yibin.YibinMainFragment;
import com.yunbiao.ybbusstopplate.utils.CommonUtils;
import com.yunbiao.ybbusstopplate.utils.LeShanUtils;
import com.yunbiao.ybbusstopplate.utils.ScreenPikerUtils;
import com.yunbiao.ybbusstopplate.utils.SmdtUtils;
import com.yunbiao.ybbusstopplate.utils.SpTool;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMessage;
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMsgTool;
import com.yunbiao.ybbusstopplate.utils.eventbus.EventTAG;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";

    private SecondaryPresentation secondaryPresentation;

    @Override
    public void setContentView(int layoutResID) {
        setOpaqueSystemBar(true,true);
        super.setContentView(layoutResID);
    }

    public void setOpaqueSystemBar(boolean immersiveBar,boolean fullScreen){
        //设置状态栏和导航栏为深色
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            WindowInsetsController windowInsetsController = getWindow().getDecorView().getWindowInsetsController();
            if(windowInsetsController != null){
                if(immersiveBar){
                    windowInsetsController.setSystemBarsAppearance(1,1);
                    windowInsetsController.setSystemBarsAppearance(1 << 1,1 << 1);
                }
                if(fullScreen){
                    windowInsetsController.hide(WindowInsets.Type.statusBars());
                    windowInsetsController.hide(WindowInsets.Type.navigationBars());
                }
            }
        }
    }

    @Override
    public int getLayoutViewId() {
        return R.layout.activity_home;
    }

    @Override
    public void initData() {
        UpgradeManager.getInstance()
                .checkUpgrade(true, null, new DefaultUpgradeStrategyRequestCallback());

        UiMessageUtils.getInstance().addListener(777,uiMessageCallback);
        EventBus.getDefault().register(this);

        HYAdvert.init(APP.Companion.getAppContext());

        HeartBeatClient.getInstance();

        //是否开启云服务器
        startServer();

        // 是否有副屏幕
        startScreenTypeServer();

        if (SpTool.Companion.getDoubleScreen()) {
            Display secondaryDisplay = SecondaryPresentation.getSecondaryDisplay(this);
            if(secondaryDisplay != null && (secondaryPresentation == null || !secondaryPresentation.isShowing())){
                secondaryPresentation = new SecondaryPresentation(this,secondaryDisplay);
            }
            secondaryPresentation.show();
        }

        KeepAliveService.Companion.startKeepAliveService(this);

        //大连
        if(BuildConfig.FLAVOR_TYPE == FlavorType.DALIAN){
            Config.DeviceType deviceType = Config.getDeviceType();
            if (deviceType.equals(Config.DeviceType.NODE_SITE_PLATE)) {
                FragmentUtils.replace(getSupportFragmentManager(),new DalianNodeSiteFragment(),R.id.fl_home);
            } else {
                FragmentUtils.replace(getSupportFragmentManager(),new DalianHeadInfoFragment(),R.id.fl_home);
            }
        }
        //奉贤
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.FENGXIAN){
            Config.DeviceType deviceType = Config.getDeviceType();
            if (deviceType.equals(Config.DeviceType.NODE_SITE_PLATE)) {
                FragmentUtils.replace(getSupportFragmentManager(),new FengxianNodeSiteFragment(),R.id.fl_home);
            } else {
                FragmentUtils.replace(getSupportFragmentManager(),new FengxianHeadInformationFragment(),R.id.fl_home);
            }
        }
        //西班牙
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.SPAIN){
            FragmentUtils.replace(getSupportFragmentManager(),new SpainMainFragment(),R.id.fl_home);
        }
        //验证界面
        else if(TextUtils.isEmpty(SpTool.Companion.getAppSerialNumber())){
            FragmentUtils.replace(getSupportFragmentManager(),new VerifyFragment(),R.id.fl_home);
        }

        //三分屏
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.IS_THREE_AREA){
            FragmentUtils.replace(getSupportFragmentManager(),new ThreeAreaMainFragment(),R.id.fl_home);
        }

        //乐山
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
            LeShanUtils.syncTime(new Observer<List<Integer>>() {
                @Override
                public void onSubscribe(Disposable d) {
                    findViewById(R.id.pb_loading).setVisibility(View.VISIBLE);
                }

                @Override
                public void onNext(List<Integer> t) {
                    int time = SmdtUtils.getInstance().setTime(t.get(0), t.get(1), t.get(2), t.get(3), t.get(4));
                    Log.d(TAG, "onNext: 校时：" + time);

                    Fragment fragment;
                    if(BuildConfig.IS_LESHAN_SELF){
                        fragment = new LeshanMainFragment();
                    } else {
                        fragment = new MainFragment();
                    }
                    FragmentUtils.replace(getSupportFragmentManager(),fragment,R.id.fl_home);

                    findViewById(R.id.pb_loading).setVisibility(View.GONE);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {
                    findViewById(R.id.pb_loading).setVisibility(View.GONE);
                }
            });
        }
        //中航讯
        else if(SpTool.Companion.getConfigSerialPortType() == SerialPortConfig.TYPE_ZHX){
            if(ScreenUtils.isPortrait()){
                MainFragment mainFragment = new MainFragment();
                FragmentUtils.replace(getSupportFragmentManager(),mainFragment,R.id.fl_home);
                View view = mainFragment.getView();
                if(view != null){
                    view.post(() -> ZHXPortAgreement.getInstance().loadCache());
                }
            } else {
                FragmentUtils.replace(getSupportFragmentManager(),new YibinMainFragment(),R.id.fl_home);
            }
        }
        //普通版本
        else {
            FragmentUtils.replace(getSupportFragmentManager(),new MainFragment(),R.id.fl_home);
        }

        //创建缓存文件夹
        CommonUtils.getInstance().makesCacheFiles();

        test();
    }

    private void startScreenTypeServer() {
        int screenType = ScreenPikerUtils.getScreenType();
        switch (screenType) {
            case 0:
                  ServerSocket.getInstance().start();
                break;
            case 1:
//                Timer timer= new Timer();
//                TimerTask timerTask = new TimerTask() {
//                    @Override
//                    public void run() {
//                        ClientSocket.getInstance().startAutoConnect();
//                        ClientSocket.getInstance().setSocketCallback(new SocketMessage());
//                    }
//                };
//                timer.schedule(timerTask,1000);
                ClientSocket.getInstance().startAutoConnect();
                break;
            case -1:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UiMessageUtils.getInstance().removeListener(777,uiMessageCallback);
        EventBus.getDefault().unregister(this);

        if(secondaryPresentation != null && secondaryPresentation.isShowing()){
            secondaryPresentation.dismiss();
            secondaryPresentation = null;
        }

        //关闭串口
        SerTool.Companion.closePort();

        //关闭通信失败dialog
        LetterErrorDialogTool.Companion.dismissLetterErrorDialog();

        try {
            ServiceManager.getInstance().stopService();
        } catch (Exception e) {
        }
    }

    private void test(){
        if(!BuildConfig.DEBUG){
            return;
        }

        findViewById(R.id.btn_list).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_next).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_query).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_up).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_down).setVisibility(View.VISIBLE);

        ZHIDAParser zhidaParser = new ZHIDAParser();
//        BASHITONGParser bashitongParser = new BASHITONGParser();

//        TONGDA2020Parser tongda2020Parser = new TONGDA2020Parser();

        findViewById(R.id.btn_list).setOnClickListener(v -> {
//            tongda2020Parser.test();
//            ZHXPortAgreement.getInstance().test1();
            EventBus.getDefault().post(ZHXPortAgreement.getInstance());
            EventBus.getDefault().post(LSPortAgreement.getInstance());
//            zhidaParser.test2();
//            bashitongParser.test1();
        });
        findViewById(R.id.btn_query).setOnClickListener(v -> {
//            zhidaParser.test1();
            zhidaParser.test1();
//            throw new RuntimeException("Test");
        });
        AtomicInteger atomicInteger = new AtomicInteger(0);
        findViewById(R.id.btn_next).setOnClickListener(v -> {
            UiMessageUtils.getInstance().send(ZHXPortAgreement.Event.BROAD_SITE.ordinal(), new Object[]{"","",atomicInteger.incrementAndGet()});
        });
    }

    private final UiMessageUtils.UiMessageCallback uiMessageCallback = uiMessage -> {
        int[] timeArray = (int[]) uiMessage.getObject();
        int seconds = timeArray[timeArray.length - 1];
        Log.d(TAG, "秒数: " + seconds);
        long delay = 60 - seconds - 5;
        Log.d(TAG, "延迟重启: " + delay);
        long lastTime = System.currentTimeMillis();
        ThreadUtils.executeByCachedWithDelay(new ThreadUtils.SimpleTask<Integer>() {
            @Override
            public Integer doInBackground() throws Throwable {
                Log.e(TAG, "doInBackground: 设置时间");
                return SmdtUtils.getInstance().setTime(timeArray[0], timeArray[1], timeArray[2], timeArray[3], timeArray[4]);
            }

            @Override
            public void onSuccess(Integer integer) {
                Log.d(TAG, "onSuccess: " + System.currentTimeMillis() + " --- " + lastTime);
                //判断设置后时间比设置前时间超过30秒就重启
                if (Math.abs(System.currentTimeMillis() - lastTime) > 30 * 1000) {
                    Log.d(TAG, "onSuccess: 设置时间重启");
                    AppUtils.relaunchApp(true);
                }
            }
        }, delay, TimeUnit.SECONDS);
    };

    private void startServer(){
        if(!SpTool.Companion.getConfigAdvertServerType()){
            return;
        }

        String serverAddress = SpTool.Companion.getServerAddress();
        String serverPort = SpTool.Companion.getServerPort();
        if(TextUtils.isEmpty(serverAddress) || TextUtils.isEmpty(serverPort)){
            return;
        }

        Constants.initConstant(serverAddress,serverPort);
        //true代表跟服务器不一样 更新布局
        TYTool.downloadResource();

        CommonUtils.saveBroadInfo();

        ServiceManager.getInstance().init(this, new CoreInfoHandler(), new ServiceManager.getUserNameCallback() {
            @Override
            public String getUserName() {
                return HeartBeatClient.getDeviceNo();
            }
            @Override
            public String getCommunicationAddress() {
                return serverAddress;
            }
            @Override
            public String getCommunicationPort() {
                return Constants.XMPP_PORT;
            }
        });
        ServiceManager.getInstance().startService();

        try {
            ServiceManager.getInstance()
                    .registerObserver(connected ->
                            Log.e("xmpp", "start: ---------it-------->" + connected)
                    );
        } catch (Exception e){
            Log.d(TAG, "ServiceManager.getInstance().registerObserver exception ",e);
        }
    }

    private long mExitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(BuildConfig.isRefactoring){
                if(FragmentUtils.dispatchBackPress(getSupportFragmentManager())){
                    return true;
                }

                if(System.currentTimeMillis() - mExitTime > 2000){
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    //并记录下本次点击“返回键”的时刻，以便下次进行判断
                    mExitTime = System.currentTimeMillis();
                } else {
                    //关闭保活程序
                    KeepAliveService.Companion.stopKeepAliveService(this);
                    Disposable subscribe = Observable
                            .timer(3, TimeUnit.SECONDS)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doOnSubscribe(disposable -> {
                                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                                progressDialog.setMessage("正在退出...");
                                progressDialog.setCancelable(false);
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.show();
                            })
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {
                                    AppUtils.exitApp();
                                }
                            });
                }
                return true;
            }

            List<FragmentUtils.FragmentNode> allFragments = FragmentUtils.getAllFragments(getSupportFragmentManager());
            for (FragmentUtils.FragmentNode allFragment : allFragments) {
                Fragment fragment = allFragment.getFragment();
                if(fragment instanceof LogFragment){
                    FragmentUtils.remove(fragment);
                    return true;
                }
            }

            for (FragmentUtils.FragmentNode allFragment : allFragments) {
                Fragment fragment = allFragment.getFragment();
                if(fragment instanceof ConfigFragment){
                    FragmentUtils.remove(fragment);
                    return true;
                }
            }

            if(Companion.getOnBackKeyListener() != null){
                Companion.getOnBackKeyListener().onBack();
                return true;
            }

            if(System.currentTimeMillis() - mExitTime > 2000){
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
                return true;
            }
        } else if(keyCode == KeyEvent.KEYCODE_MENU){
            try {
                List<FragmentUtils.FragmentNode> allFragments = FragmentUtils.getAllFragments(getSupportFragmentManager());
                for (FragmentUtils.FragmentNode allFragment : allFragments) {
                    if(allFragment.getFragment() instanceof MainFragment){
                        EventMsgTool.Companion.getInstance().postShowConfig();
                    }
                }
            } catch (Exception e){
                Log.d(TAG, "onKeyDown: ",e);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventResult(EventMessage eventMessage){
        Log.d(TAG, "BuildConfig.FLAVOR_TYPE: " + BuildConfig.FLAVOR_TYPE);
        Log.d(TAG, "eventMessage.msgTag 路？ " + eventMessage.getMsgTag());
        switch (eventMessage.getMsgTag()) {
            case EventTAG.EVENT_TOMAIN:{
                Fragment fragment;
                if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN && BuildConfig.IS_LESHAN_SELF){
                    fragment = new LeshanMainFragment();
                } else {
                    fragment = new MainFragment();
                }
                FragmentUtils.replace(getSupportFragmentManager(), fragment, R.id.fl_home,
                        R.anim.fragment_slide_right_in, R.anim.fragment_slide_left_out
                );
                break;
            }
        }
    }
}
